<template>
  <view class="img-upload-wrap">
    <view class="img-upload">
      <view class="img-upload_input" @tap="uploadImg">+</view>
    </view>
  </view>
</template>
<script>
import { UPLOAD_FILE } from '@/api/cms';
import { domain } from '@/config';

export default {
  props: {
    count: {
      type: Number,
      default: 10,
    },
  },
  methods: {
    uploadImg() {
      const vm = this;
      const pics = [];
      uni.chooseImage({
        count: 10,
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: res => {
          if (res.tempFilePaths.count === 0) {
            return;
          }
          for (let i = 0; i < res.tempFilePaths.length; i++) {
            // 验证格式
            if (!/.(jpg|jpeg|png)$/i.test(res.tempFilePaths[i])) {
              uni.showToast('图片格式不对，格式必须是jpeg,jpg,png中的一种');
              return;
            }
            pics.push(res.tempFilePaths[i]);
          }
          vm.postImg({
            pics,
          });
        },
      });
    },
    postImg(data) {
      // 图片上传
      uni.showLoading({
        title: '上传中...', // 提示的内容,
        mask: true, // 显示透明蒙层，防止触摸穿透,
      });

      wx.uploadFile({
        url: domain + UPLOAD_FILE,
        filePath: data.pics[0],
        name: 'file',
        success: res => {
          this.$emit('listenImg', JSON.parse(res.data).data);
          uni.hideLoading();
        },
        fail: () => {
          uni.hideLoading();
        },
      });
    },
  },
};
</script>
<style lang="less">
.img-upload-wrap {
  width: 200rpx;
  height: 200rpx;
  .img-upload {
    width: 100%;
    height: 100%;
  }

  .img-upload_input {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    font-size: 40rpx;
  }
}
</style>
